<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\workWechat;

use app\common\model\platform\Platform;
use think\facade\Cache;
use think\facade\Session;

trait WorkWechatOauth
{
    /**
     * 获取用户企业微信授权信息
     * @param $force_oauth bool 是否强制授权
     * @param $userinfo bool 是否获取用户信息
     * @return false|mixed|string
     * @throws \Exception
     */
    public function getUser($force_oauth = true, $userinfo = true)
    {
        $auth = (new Platform())->where(['plaid' => get_plaid()])->value('auth_type');//授权模式
        $callback = $this->getCallBackUrl();
        Cache::set($this->getKey('target_url'), request()->url(), 600);
        $scope = $userinfo ? 'snsapi_privateinfo' : 'snsapi_base';
        $work_wx_user = Cache::get($this->getKey('work_wx_user'));
        if (!empty($work_wx_user)) {
            return $work_wx_user;
        } else {
            if (!$force_oauth) return false;
            if ($auth == 0 && $this->plaid) {
                $redirect = $this->getAuthUrl($scope);
            } else {
                // 服务商
                $app = (new WorkWechatOpen())->getOpenApp();
                $redirect = $app->corp->getOAuthRedirectUrl($callback, $scope, 'STATE');
            }
        }
        to($redirect);
        return '';
    }

    public function getCallBackUrl()
    {
        $vars = ['p' => $this->plaid, 'sid' => Session::getid()];
        $topuid = input('topuid', 0);
        if ($topuid) $vars['topuid'] = $topuid;
        if ($this->addon_name) $vars['addon'] = $this->addon_name;
        return url('/'.config('hiduoke.work_wechat_app') . "/oauth/callback", $vars)->domain(true)->build();
    }

    /**
     * 获取缓存key
     * @param $string
     * @return string
     */
    protected function getKey($string)
    {
        return $string . Session::getid() . '_' . $this->plaid;
    }

    public function getAuthUrl($scope, $state = '')
    {

        // 网页授权登录
        if (empty($this->agentId)) {
            $queries = [
                'appid'         => $this->getConfig()['corp_id'],
                'redirect_uri'  => $this->getCallBackUrl(),
                'response_type' => 'code',
                'scope'         => $scope,
                'state'         => $state,
            ];
            if ($scope) {
                $queries['agentid'] = $this->getConfig()['agent_id'];
            }
            return sprintf('https://open.weixin.qq.com/connect/oauth2/authorize?%s#wechat_redirect', http_build_query($queries));
        }
    }

}
